import React from 'react';
import { SelfDiv } from "./style"
import { Form, Input, Button, Upload, message } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { useState, useRef } from "react"
import { getStorage } from "../../../utils/LocalStorage"

const layout = {
    labelCol: {
        span: 7,
    },
    wrapperCol: {
        span: 10,
    },
};
const tailLayout = {
    wrapperCol: {
        offset: 11,
        span: 16,
    },
};

//图像处理函数
function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}
//图片格式检查函数
function beforeUpload(file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('只能上传JPG/PNG格式!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('图片大小必须小于2MB!');
    }
    return isJpgOrPng && isLt2M;
}

const Index = () => {

    const [loading, setLoading] = useState(false)
    const [imageUrl, setImageUrl] = useState("");

    //设置新密码，新密码确认值
    // const [ newPassword,setNewpassword ] = useState("")
    // const [ affirmpassword,setAffirmpassword ] = useState("")
    const newpassRef = useRef();
    const affirepassRef = useRef();

    //从本地存储获取username的值
    const [username, setUsername] = useState(() => {
        return getStorage("username") ? getStorage("username") : ""
    })
    const [phonenumber, setPhonenumber] = useState(() => {
        return getStorage("phonenumber") ? getStorage("phonenumber") : ""
    })
    const [canChangePhonenumber, setCanChangePhonenumber] = useState(true)
    //账号信息修改处理函数---成功
    const onFinish = (values) => {
        console.log('Success:', values);
    };
    //账号信息修改处理函数---失败
    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };

    //照片处理函数
    const handleChange = info => {
        if (info.file.status === 'uploading') {
            setLoading(!loading)
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj, imageUrl => {
                setImageUrl(imageUrl)
                setLoading(false)
            }
            );
        }
    };

    //控制能否修改手机号码的函数
    const handleCanchange = () => {
        setCanChangePhonenumber(!canChangePhonenumber)
    }

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>上传头像</div>
        </div>
    );

    // 手机号码校验规则，只能为十一位、纯数字手机号码。
    const phonenumberRule = [
        {
            required: true,
            message: '请修改您的手机号!',
        },
        {
            len: 11,
            message: "请输入11位电话号码"
        },
        {
            validator(rule, value) {

                if (!Number(value) && value.length !== 0) {
                    return Promise.reject(new Error("请输入正确的手机号"))
                } else {
                    return Promise.resolve()
                }

            }
        }
    ]
    const newpasswordRule = [
        {
            required: true,
            message: '请使用规范密码',
        },
        {
            min: 6,
            max: 11,
            message: "请输入六到十一位密码值"
        },
        {
            validator(rule, value) {
                if (/^(?![A-Za-z]+$)(?![A-Z\d]+$)(?![A-Z\W]+$)(?![a-z\d]+$)(?![a-z\W]+$)(?![\d\W]+$)\S{6,}$/.test(value)) {
                    return Promise.resolve()
                } else {
                    return Promise.reject(new Error("密码需要含数字、大小写字母、特殊字符中的至少3种组成"))
                }
            }
        }
    ]
    return (

        <SelfDiv>
            <div className="head">账户设置</div>
            <div className="SelfBody">



                {/* 修改头像 */}
                <div className="headPic">
                    <Upload style={{ margin: "0 auto" }}
                        name="avatar"
                        listType="picture-card"
                        className="avatar-uploader"
                        showUploadList={true}
                        //这里是照片要提交的地址
                        action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                        beforeUpload={beforeUpload}
                        onChange={handleChange}
                    >
                        {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                    </Upload>
                </div>
                {/* 修改账户信息 */}
                <Form
                    {...layout}
                    name="basic"
                    initialValues={{
                        username: username,
                        phonenumber: phonenumber.substring(0, 3) + "****" + (phonenumber.substring(8, 4)),
                    }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                >
                    <Form.Item
                        label="账号"
                        name="username"

                        rules={[
                            {
                                required: true,
                                message: '请修改您的账号!',
                            },
                        ]}
                    >
                        <Input disabled={true} />
                    </Form.Item>


                    <Form.Item
                        label="手机号"
                    >
                        <Form.Item
                            name="phonenumber"
                            noStyle
                            rules={phonenumberRule}
                        >
                            <Input disabled={canChangePhonenumber} />
                        </Form.Item>
                        <span onClick={handleCanchange} style={{ position: "absolute", width: "2rem", bottom: "0", textDecoration: "underline", color: "red" }}>修改</span>
                    </Form.Item>

                    <Form.Item
                        label="旧密码"
                        name="oldpasswrod"
                        rules={[
                            {
                                required: true,
                                message: '输入正确的密码',
                            },

                        ]}
                    >
                        <Input.Password />
                    </Form.Item>

                    <Form.Item
                        label="新密码"
                        name="newpassword"
                        rules={newpasswordRule}
                    >
                        <Input.Password ref={newpassRef} />
                    </Form.Item>

                    <Form.Item
                        label="确认密码"
                        name="affirmpassword"
                        rules={[
                            {
                                required: true,
                                message: '请确保两次密码保持一致',
                            },
                            {
                                validator(rule, value) {
                                    if (newpassRef.current.state.value !== affirepassRef.current.state.value) {
                                        return Promise.reject(new Error("两次密码请保持一致"))
                                    } else {
                                        return Promise.resolve()
                                    }
                                }
                            }
                        ]}
                    >
                        <Input.Password ref={affirepassRef} />
                    </Form.Item>


                    <Form.Item {...tailLayout}>
                        <Button type="primary" htmlType="submit">
                            确定
                    </Button>
                    </Form.Item>
                </Form>
            </div>
        </SelfDiv>
    );
}

export default Index;

